package id.co.shuba.spamobile.task;

import id.co.shuba.spamobile.R;
import id.co.shuba.spamobile.Sessions;
import id.co.shuba.spamobile.activities.DownloadActivity;
import id.co.shuba.spamobile.services.WebServiceHelper;
import id.co.shuba.spamobile.util.Base64;
import id.co.shuba.spamobile.util.Str;

import java.util.HashMap;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.util.Log;
import android.view.ContextThemeWrapper;

public class LogoutTask extends AsyncTask<String, Integer, Boolean> {
	private Activity context;
	private boolean exit;		
	ProgressDialog dialog;
	private boolean upload;
	
	public LogoutTask(boolean exit, boolean upload, ProgressDialog dialog, Activity context) {
		this.exit = exit;
		this.dialog = dialog;
		this.context = context;
		this.upload = upload;
	}						
	
	public void setDialog(ProgressDialog dialog) {			
		this.dialog = dialog;
		if (getStatus() == Status.RUNNING && !dialog.isShowing())
			dialog.show();
	}
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();			
		if (!dialog.isShowing())
			dialog.show();
	}
	
	@Override
	protected Boolean doInBackground(String... params) {
		WebServiceHelper ws = new WebServiceHelper(context);
		HashMap<String, Object> properties = new HashMap<String, Object>();
		properties.put("aoCode", Sessions.getUser(context).getAoCode());
		try {
			String result = ws.Call("Logout", properties).toString();
			String strJSON = new String(Base64.decode(result, Base64.GZIP)); 									
			
			JSONObject res = new JSONObject(strJSON);
			String error = res.getString("error");
			
			if (!Str.isNullOrEmpty(error) && !"null".equals(error))
				throw new Exception(error);
			
			return true;
		} catch (Exception e) {
			Log.e("Logout", e.getMessage());
			e.printStackTrace();							
			return false;
		}						
	}
	
	private void logout() {
		Intent intent = new Intent(context, DownloadActivity.class);
		intent.putExtra(DownloadActivity.PARAMETER_OPTION,
				DownloadActivity.UPLOAD_ALL);
		intent.putExtra(DownloadActivity.PARAMETER_AUTO_START, true);		
		intent.putExtra(DownloadActivity.PARAMETER_EXIT_WHEN_DONE, true);
		intent.putExtra(DownloadActivity.PARAMETER_GO_TO_LOGIN_WHEN_DONE, true);
		context.startActivity(intent);
		context.finish();
	}
	
	private void upload(boolean exit) {
		Intent intent = new Intent(context, DownloadActivity.class);
		intent.putExtra(DownloadActivity.PARAMETER_OPTION,
				DownloadActivity.UPLOAD_ALL);
		intent.putExtra(DownloadActivity.PARAMETER_AUTO_START, true);
		if (exit)
			intent.putExtra(DownloadActivity.PARAMETER_EXIT_WHEN_DONE, true);
		
		context.startActivity(intent);
	}	

	@Override
	protected void onPostExecute(Boolean result) {
		Context ctx = null;
		if (dialog != null) {
			ctx  = dialog.getContext();
			
			if (dialog.isShowing())
				dialog.dismiss();
		}
		
		if (dialog != null && dialog.isShowing())
			dialog.dismiss();
		
		if (result) {			
			if (exit) {
				if (upload) {
					upload(true);
				}
            	context.finish();     
			} else {
				logout();
			}
		} else {				
			if (ctx != null) {
				final Context x = ctx;
				new AlertDialog.Builder(new ContextThemeWrapper(ctx,
						R.style.Theme_Sherlock_Light_Dialog))
		        .setIcon(android.R.drawable.ic_dialog_alert)
		        .setTitle(R.string.error)
		        .setMessage("Gagal logout, tidak dapat terhubung ke server")
		        .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface d, int which) {
		            	d.dismiss();	            	
		            }
		        })
		        .setNeutralButton("Keluar", new DialogInterface.OnClickListener() {				
					@Override
					public void onClick(DialogInterface d, int which) {
						d.dismiss();
						context.finish();
					}
				})
		        .setPositiveButton(R.string.retry, new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface d, int which) {			            	
		            	d.dismiss();
		            	
		            	ProgressDialog pd = new ProgressDialog(x);
		            	pd.setMessage("Logging out...");
		            	pd.setCancelable(false);
		    			new LogoutTask(exit, upload, dialog, context).execute("");
		            }
		        })        
		        .show();
			}
		}
	}
}
